package com.zhongjh.mvvmrapid.binding.viewadapter.view;

import android.view.View;

import androidx.databinding.BindingAdapter;

import com.zhongjh.mvvmrapid.binding.command.BindingCommand;

public class ViewAdapter {

    /**
     * requireAll 是意思是是否需要绑定全部参数, false为否
     * View的onClick事件绑定
     * onClickCommand 绑定的命令,
     * isThrottleFirst 是否 不开启防止过快点击
     */
    @BindingAdapter(value = {"onClickCommand", "isThrottleFirst"}, requireAll = false)
    public static void onClickCommand(View view, final BindingCommand<Void> clickCommand, final boolean isThrottleFirst) {
        if (isThrottleFirst) {
            view.setOnClickListener(v -> {
                if (clickCommand != null) {
                    clickCommand.execute();
                }
            });
        } else {
            view.setOnClickListener(new ThrottleOnClickListener() {
                @Override
                protected void onClick() {
                    if (clickCommand != null) {
                        clickCommand.execute();
                    }
                }
            });
        }
    }

    /**
     * view的onLongClick事件绑定
     */
    @BindingAdapter(value = {"onLongClickCommand"}, requireAll = false)
    public static void onLongClickCommand(View view, final BindingCommand<Void> clickCommand) {
        view.setOnLongClickListener(v -> {
            if (clickCommand != null) {
                clickCommand.execute();
            }
            return false;
        });
    }

    /**
     * 回调控件本身
     *
     */
    @BindingAdapter(value = {"currentView"}, requireAll = false)
    public static void replyCurrentView(View currentView, BindingCommand<View> bindingCommand) {
        if (bindingCommand != null) {
            bindingCommand.execute(currentView);
        }
    }

    /**
     * view是否需要获取焦点
     */
    @BindingAdapter({"requestFocus"})
    public static void requestFocusCommand(View view, final Boolean needRequestFocus) {
        if (needRequestFocus) {
            view.setFocusableInTouchMode(true);
            view.requestFocus();
        } else {
            view.clearFocus();
        }
    }

    /**
     * view的焦点发生变化的事件绑定
     */
    @BindingAdapter({"onFocusChangeCommand"})
    public static void onFocusChangeCommand(View view, final BindingCommand<Boolean> onFocusChangeCommand) {
        view.setOnFocusChangeListener((v, hasFocus) -> {
            if (onFocusChangeCommand != null) {
                onFocusChangeCommand.execute(hasFocus);
            }
        });
    }

    /**
     * view的显示隐藏
     */
    @BindingAdapter(value = {"isVisible"}, requireAll = false)
    public static void isVisible(View view, final Boolean visibility) {
        if (visibility) {
            view.setVisibility(View.VISIBLE);
        } else {
            view.setVisibility(View.INVISIBLE);
        }
    }



}
